<!--
*@Author: QWP
*@Description: 车辆保险登记弹窗
*@Date 2024-09-18 11:13
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :hideBtns="isCheck == true || isReport ? ['confirm'] : []"
    :confirmLoading="state.formLoading"
    @submit="submit"
    @close="dialogClose"
  >
    <u-busi-card title="车辆信息">
      <u-form
        ref="formRef"
        :elements="state.elements"
        :model="state.form"
        :disabled="isReport"
      ></u-form>
    </u-busi-card>
    <u-busi-card title="保险购买">
      <u-form
        ref="bxFormRef"
        :elements="state.bxelements"
        :model="state.bxform"
        :disabled="isReport"
      ></u-form>
    </u-busi-card>
    <u-busi-card title="相关附件/凭证">
      <u-form
        ref="form3"
        :elements="state.fileEls"
        :model="state.fileForm"
        :disabled="isReport"
      ></u-form>
    </u-busi-card>
  </u-dialog>
</template>
<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave} from "vue-router";
import { useBaseStore, useLoginStore } from '@/store'
import { storeToRefs } from "pinia";
import { getLicencePlate } from '@/service/administration/driver'
import { messageC, numberC, nullC } from '@/util/common'
import { addC } from '@/util/computePtrcision.ts'
import * as insureApi from '@/service/administration/carInsure'
import dayjs from 'dayjs';

const props = defineProps<{
  isCheck?: boolean,
  keyid: string
}>()

const attrs = useAttrs()
const route = useRoute()

const { userInfo } = storeToRefs(useLoginStore())
const { VEHICLE_MODEL, VEHICLE_TYPE, ISPROXY } = storeToRefs(useBaseStore())

// 是否是报表
const isReport = computed(() => route.params.pType == 2)

const formItemProps = {
  labelWidth: '110px',
  colon: false
}

const emits = defineEmits(['success'])

const baseData = ref<{
  [key: string]: any[]
}>({
  cpdata: [],
  bxgsData: []
})

const formRef = ref()
const bxFormRef = ref()

const state = reactive({
  form: {
    vehiclenumber: '',
    keyid: '',

    vehicleadminname: '',
    ssdeptname: '',
    vehiclemodel: '',
    vehicletype: '',
    isproxy: 0,
    exhaustvolume: '',

    lastinsureffectdate: '',
    lastinsurmechanismid: '',
    lastinsurmechanism: '',
    lastinsurduedate: '',
    lastinsuramt: ''
  },
  elements: [
    { label: '车牌号', key: 'keyid', col: { span:8,}, element: 'select', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: { 
        allowClear: false,
        options: computed(() => baseData.value.cpdata), 
        fieldNames: { label: 'platenumber', value: 'keyid' } ,
        onChange: (val, o) => {
          state.form.vehiclenumber = val; // 设置车辆的ID
          state.bxform.fkvehicleid = val; // 设置保险对应的车id
          let carInfo = baseData.value.cpdata.find((s) => s.keyid === val) || {}
          state.bxform.vehiclenumber = carInfo.platenumber;
          getAddData(state.form.vehiclenumber);
        }
      },
    },
    { label: '车辆管理员', key: 'vehicleadminname', col: { span:8,}, element: 'input', 
      formItemProps: { ...formItemProps,},
      componentProps: { options: [], disabled: true },
    },
    { label: '管理部门', key: 'ssdeptname', col: { span:8,}, element: 'input', 
      formItemProps: { ...formItemProps, },
      componentProps: { options: [], disabled: true },
    },
    { label: '车型', key: 'vehiclemodel', col: { span:8,}, element: 'select', 
      formItemProps: { ...formItemProps,},
      componentProps: { options: VEHICLE_MODEL.value, disabled: true },
    },
    { label: '车辆类型', key: 'vehicletype', col: { span:8,}, element: 'select', 
      formItemProps: { ...formItemProps, },
      componentProps: { options: VEHICLE_TYPE.value, disabled: true },
    },
    { label: '是否代管', key: 'isproxy', col: { span:8,}, element: 'select', 
      formItemProps: { ...formItemProps, },
      componentProps: { options: ISPROXY.value, disabled: true },
    },
    { label: '排量', key: 'exhaustvolume', col: { span:8,}, element: 'number', 
      formItemProps: { ...formItemProps, },
      componentProps: {
        precision: 2, disabled: true 
      }
    },
    { label: '上次保险生效日', key: 'lastinsureffectdate', col: { span:8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps, },
      componentProps: { disabled: true }
    },
    { label: '上次保险公司', key: 'lastinsurmechanism', col: { span:8,}, element: 'input', 
      formItemProps: { ...formItemProps, },
      componentProps: { disabled: true }
    },
    { label: '上次保险到期日', key: 'lastinsurduedate', col: { span:8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps, },
      componentProps: { disabled: true }
    },
    { label: '上次保费', key: 'lastinsuramt', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, },
      componentProps: { disabled: true }
    },
  ],

  bxform: {
    insuramt: 0,
    insuramt1: 0,
    insuramt2: 0,
    insuramt3: 0,
    insuramt4: 0,
    insurancedate: '',
    remarke: '',
    fkmechanismid: '',
    mechanismname: '',
    insureffectdate: '',
    insurduedate: '',
    lastinsurduedate: ''
    // isreimburse: ''
  },
  bxelements: [
    { label: '购买日期', key: 'insurancedate', col: { span:8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps, required: true  },
      componentProps: {
        disabledDate: (current)=> {
          return current && current > dayjs().endOf('day')
        },
        onChange: () => {
          if(!state.form.lastinsureffectdate) {
            state.bxform.insureffectdate = '';
            state.bxform.insurduedate = '';
          }
        }
      }
    },
    { label: '保险生效日期', key: 'insureffectdate', col: { span:8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        disabledDate: (current)=> {
          return current && current < dayjs(state.bxform.insurancedate).subtract(1, 'day').endOf('day')
        },
        onChange: (e) => {
          state.bxform.insurduedate =  e ? getNextYear(e) : '';
          bxFormRef.value.form.validateFields(['insurduedate'])
        }
      }
    },
    { label: '保险到期日期', key: 'insurduedate', col: { span:8,}, element: 'datepicker', 
      formItemProps: { ...formItemProps, required: true },
    },
    { label: '保险公司', key: 'fkmechanismid', col: { span:8,}, element: 'select', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: computed(() => baseData.value.bxgsData),
        fieldNames: { label: 'mechanismname', value: 'keyid' } ,
        onChange: (val, o) => {
          state.bxform.mechanismname = baseData.value.bxgsData.find((item) => item.keyid == val).mechanismname;
        }
      }
    },
    { label: '保费', key: 'insuramt', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        disabled: true, addonAfter: '元'
      }
    },
    { label: '第三者责任险', key: 'insuramt2', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: { 
        addonAfter: '元'
      }
    },
    { label: '交强险', key: 'insuramt1', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: { 
        addonAfter: '元'
      }
    },
    { label: '车辆损失险', key: 'insuramt3', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: { 
        addonAfter: '元'
      }
    },
    { label: '其他保费', key: 'insuramt4', col: { span:8,}, element: 'money', 
      formItemProps: { ...formItemProps, required: true },
      componentProps: { 
        addonAfter: '元'
      }
    },
    { label: '备注说明', key: 'remarke', col: { span: 24,}, element: 'textarea', 
      formItemProps: { ...formItemProps,},
    },
  ],

  fileForm: {},
  fileEls: [
    { label: '', key: 'appendixSaveVOList', col: { span: 24,}, element: 'file', 
      formItemProps: { ...formItemProps, },
      componentProps: {
        fileParams: { biztype: '3', bucket: 'VEHICLE_BIZ_TYPE_INSURANCE', }
      }
    },
  ],

  formLoading: false,
})

// 保费计算
watch(() => state.bxform, (nval, oval) => {
  let total = 0;
  if(Object.keys(state.bxform).length != 0) {
    for(let i = 1; i <= 4; i++) {
      total = addC(total, numberC(state.bxform[`insuramt${i}`] || '0'))
    }
  }
  state.bxform.insuramt = total
}, { deep: true })

// 保存
async function submit() {
  try {
    await formRef.value.form.validate()
    await bxFormRef.value.form.validate()
  } catch (error) {
    messageC("请先将表单信息填写完毕！");
    return
  }

  const url = state.bxform.keyid ? 'update' : 'add';
  state.formLoading = true;
  try {
    const res = await insureApi[url]({...state.form, ...state.bxform, ...state.fileForm })
    state.formLoading = false;
    if (res.code == 0) {
      messageC(res.msg, 'success');
      emits('success');
      dialogClose()
    } else {
      messageC(res.msg, 'warning');
    }
  } catch (error) {}
  state.formLoading = false;
}

// 初始表单信息
function initFormInfo() {
  state.form.fkuserid = userInfo.value['userId']
  state.form.fkusername = userInfo.value['name']
  state.form.fkdeptid = userInfo.value['deptId']
  state.form.redeptname = userInfo.value['deptName']
  state.form.fkunitsid = userInfo.value['unitId']

}

// 查询车牌号以及车辆主键
async function getCarNum() {
  try {
    const res = await getLicencePlate()
    if(res.code == 0) {
      baseData.value.cpdata = res.data || []
    }
  } catch (error) {}
}

// 获取下一年
function getNextYear(date, subDay: number = 1) {
  return dayjs(date).add(1, 'year').subtract(subDay, 'day').format('YYYY-MM-DD');
}

// 根据所选车辆回显相关信息
async function getAddData(val) {
  try {
    state.formLoading = true;
    const ret = await insureApi.to_add(val);

    // 保险机构信息
    baseData.value.bxgsData = ret.data['mechanismList'] || [];

    // 车辆基本信息
    state.form = (ret.data.vehicleList || [{}])[0];
    state.form.fkvehicleid = val;

    // 上次保险信息
    let insurance = ret.data.lastInsurance || {};
    state.bxform = {};

    state.bxform.fkvehicleid = val;
    state.bxform.vehiclenumber = state.form.platenumber;

    // 手动处理回显字段和保存字段不一致
    state.form.lastinsureffectdate = nullC(insurance['insureffectdate']).split(' ')[0];
    state.form.insurduedate = nullC(insurance['insurduedate']).split(' ')[0];

    state.form.lastinsurmechanism = nullC(insurance['mechanismname']);
    state.form.lastinsuramt = nullC(insurance.insuramt);
    // 保险公司id
    state.form.lastinsurmechanismid = nullC(insurance.fkmechanismid);

    //新增字段
    state.bxform.insuramt1 = numberC(insurance.insuramt1);
    state.bxform.insuramt2 = numberC(insurance.insuramt2);
    state.bxform.insuramt3 = numberC(insurance.insuramt3);
    state.bxform.insuramt4 = numberC(insurance.insuramt4);

    // 自动回显下面的保险信息
    state.bxform.fkmechanismid = state.form.lastinsurmechanismid;
    state.bxform.mechanismname = state.form.lastinsurmechanism;
    state.bxform.insuramt = state.form.lastinsuramt;

    // 日期计算到下一年
    state.bxform.insureffectdate = state.form.lastinsureffectdate ? getNextYear(state.form.lastinsureffectdate, -1) : '';
    state.bxform.insurduedate = state.bxform.insureffectdate ? getNextYear(state.bxform.insureffectdate) : '';
   
  } catch(e) {}
  state.formLoading = false;
}

// 回显
async function getHxData() {
  state.formLoading = true;
  try {
    const ret = await insureApi.singleQuery(props.keyid);

    if(ret.code == 0) {
      const retData = ret.data || {};
      
      state.form = retData.vehicle || {}
      state.bxform = retData.insurance || {}
  
      if (state.bxform.insureffectdate) {
        state.form.lastinsureffectdate = state.bxform.insureffectdate.split(' ')[0];
      }
      if (state.bxform.insurduedate) {
        state.form.lastinsurduedate = state.bxform.insurduedate.split(' ')[0];
      }
  
      state.form.lastinsurmechanism = state.bxform.mechanismname;
  
      state.form.lastinsuramt = state.bxform.insuramt;

      // 保险公司id
      state.form.lastinsurmechanismid = state.bxform.fkmechanismid;
  
      // 手动处理传值字段与回显字段不一致 --- 车牌号keyid
      state.form.fkvehicleid = state.form.keyid;
      state.form.vehiclenumber = state.form.platenumber;

      state.fileForm.appendixSaveVOList = ret.data['insuranceAttach'] || []

      // 获取保险公司
      echoGetBxgsData() 
    }

  } finally { }
  state.formLoading = false;
}

// 获取保险公司信息
async function echoGetBxgsData() {
  try {
    const res = await insureApi.to_add(props.keyid);
    if(res.code == 0) {
      baseData.value.bxgsData = res.data.mechanismList || []
    }
  } catch (error) {}
}

// 弹窗关闭
function dialogClose() {
  formRef.value.form.resetFields()
  state.form = {} 
  
  bxFormRef.value.form.clearValidate()
  state.bxform = {}

  state.fileForm = {}
}

watch(() => attrs.open, (nval, oval) => {
  if (nval == true) {
    getCarNum(); // 获取车辆信息
    initFormInfo();
    state.bxform.keyid = props.keyid;
    if (state.bxform.keyid != '') {
      getHxData();
    }
  }
})

</script>
<style lang="scss">
.car-container {
  .u-busi-item {
    margin-bottom: 10px;

    .u-busi-title {
      background: unset;
    }
  }

  .el-table__body-wrapper{
    height: 100% !important;
  }
}
</style>
